package com.comment.project.json;



import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * @author liupenghui
 * @date 2018/7/12
 * @desc：
 */
public class JsonNodeToJson {
    public static void main(String[] args) throws IOException, ParseException, org.json.simple.parser.ParseException {
        String json = "{\"username\":\"tom\",\"company\":{\"companyName\":\"中华\",\"address\":\"北京\"},\"cars\":[\"奔驰\",\"宝马\"]}";

        String arrayJson = "[{\"number\":64,\"result\":\"SUCCESS\"},{\"number\":65,\"result\":\"FAILURE\"},{\"number\":66,\"result\":\"ABORTED\"},{\"number\":67,\"result\":\"SUCCESS\"}]";

        ObjectMapper mapper = new ObjectMapper();
//        Json字符串转换成JsonNode对象
        JsonNode jsonNode = mapper.readTree(json);


//        jsonNode的fieldNames方法是获取jsonNode的所有的key值
        Iterator<String> keys = jsonNode.fieldNames();
        while (keys.hasNext()) {
            String key = keys.next();
            System.out.println("key键是:" + key);
        }

        JsonNode path = jsonNode.path("sex");
        System.out.println("===" + path + "===");
        JsonNode resultValue = jsonNode.findValue("sex");
        System.out.println("===" + resultValue + "===");
        JsonNode resultPath = jsonNode.findPath("sex");
        System.out.println("===" + resultPath + "===");

//        使用jsonNode.elements();读取数组中每个node
        Iterator<JsonNode> elements = jsonNode.elements();
        while(elements.hasNext()){
            JsonNode node = elements.next();
            System.out.println(node.toString());
        }


//        JsonNode对象转换成JSON字符串
        String jsonStr = mapper.writeValueAsString(jsonNode);
        System.out.println("JsonNode--->Json:"+jsonStr);

//        JsonNode对象转换成JSON字符串
        String studentJson = "{\"stuId\":\"116\",\"stuName\":\"赵云\",\"stuAddress\":\"常山\",\"stuIQ\":\"93\"}";
        JSONParser parser = new JSONParser();
        JSONObject object1 = (JSONObject) parser.parse(studentJson);
        com.alibaba.fastjson.JSONObject object =  JSON.parseObject(studentJson);

//        JsonObject对象转换成JavaBean
        Student student = object.toJavaObject(Student.class);
//        json字符串转换成JavaBean
        Student stu = JSON.parseObject(studentJson,Student.class);



    }
}
